package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Author: 笨蛋超人不会飞
 * Date:  18:09
 */
@Service
public class DishServiceImpl implements DishService {
    @Autowired
    DishMapper dishMapper;
    @Autowired
    DishFlavorMapper dishFlavorMapper;
    @Autowired
    SetmealDishMapper setmealDishMapper;
    @Autowired
    CategoryMapper categoryMapper;
    @Override
    public void save(DishDTO dishDTO) {
        //先进行属性拷贝，把DTO中的数据拷贝到Dish中
        Dish dish=new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //调用DishMapper的save方法进行保存
        dishMapper.insert(dish);
        //获取id
        Long dishId=dish.getId();
        //使用循环，把dishDTO中的List<DishFlavor> flavors菜品口味数据分别调用mapper接口进行保存
        //非空判断
        if(dishDTO.getFlavors()!=null&&dishDTO.getFlavors().size()!=0){
            for (DishFlavor flavor : dishDTO.getFlavors()) {
                //先设置关联的id值
                flavor.setDishId(dishId);
                //调用mapper接口进行保存
                dishFlavorMapper.insert(flavor);

            }
        }
    }

    @Override
    public PageResult getAllDish(DishPageQueryDTO dishPageQueryDTO) {
        //使用分页pagehelper进行分页查询
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        //调用mapper接口进行查询
        Page<Dish> page=dishMapper.selectAllDish(dishPageQueryDTO);


        //返回结果
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    //事务
    @Transactional
    public void deleteByIds(List<Long> ids) {
        // 遍历传入的菜品ID列表，判断是否有菜品的状态是在售（1），如果是则不能删除
        for (Long id : ids) {
            // 根据菜品ID查询菜品信息
            Dish dish = dishMapper.selectById(id);
            if (dish.getStatus() == StatusConstant.ENABLE) {
                // 如果菜品状态为在售，抛出删除失败异常
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }

        // 再查看是否有套餐关联了菜品，如果关联了则不能删除
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if (setmealIds != null && setmealIds.size() != 0) {
            // 如果存在套餐关联了菜品，抛出删除失败异常
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
        }

        // 执行删除菜品操作
        for (Long id : ids) {
            // 删除菜品记录
            dishMapper.deleteById(id);
            // 同时删除菜品对应的口味记录
            dishFlavorMapper.deleteByDishId(id);
        }
    }

    @Override
    public DishVO getDishById(Long id) {
        //
        Dish dish=dishMapper.selectById(id);
        // 根据id查询口味信息
        List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(id);
        // 创建一个DishVO对象，用于封装菜品信息和口味信息
        DishVO dishVO = new DishVO();
        // 复制属性
        BeanUtils.copyProperties(dish, dishVO);
        // 设置口味信息
        dishVO.setFlavors(flavors);
        //查询菜品归属分类的分类名
        Long categoryId = dish.getCategoryId();
        Category category = categoryMapper.selectById(categoryId);
        String name=category.getName();
        dishVO.setCategoryName(name);
        return dishVO;

    }

    @Override
    public void update(DishDTO dishDTO) {
        //将DTO对象转换为Dish对象
        Dish dish=new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //更新菜品信息
        dishMapper.updateById(dish);
        //更新菜品口味信息
        Long dishId=dish.getId();
        //先删除原先的菜品口味
        dishFlavorMapper.deleteByDishId(dishId);
        //再添加新的菜品口味
        List<DishFlavor> flavors=dishDTO.getFlavors();
        //通过遍历添加
        for(DishFlavor flavor:flavors){
            dishFlavorMapper.insert(flavor);
        }

    }

    @Override
    public void changeStatus(Integer status, List<Long> ids) {
        //先查看ids是否关联了套餐，如果关联了则不能修改状态
        List<Long> setmealIds=setmealDishMapper.getSetmealIdsByDishIds(ids);
        if(setmealIds!=null&&setmealIds.size()!=0){
            throw new  DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
        }
        //如果ids中没有关联的套餐，则可以修改状态
        Dish dish=new Dish();
        dish.setStatus(status);
        dish.setId(ids.get(0));
        dishMapper.updateById(dish);
    }

    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;

    }

    @Override
    public List<Dish> list(Long categoryId) {

        Dish dish=new Dish();
        dish.setCategoryId(categoryId);
        //为了防止查询出来的菜品是处于停售状态的菜，所以查询出来的菜品状态必须是1
        dish.setStatus(StatusConstant.ENABLE);
        return dishMapper.list(dish);
    }
}
